package com.tarena.luban.demo.gateway.filters;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.function.Supplier;

//@Component
public class MyFilter02 implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("请求经过了MyFilter02...");
        // 获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        // 响应数据
        String result = "你被拦截了!!";
        // 设置响应头信息
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);
        // 最终输出的二进制流
        byte[] bytes = result.getBytes(StandardCharsets.UTF_8);
        // 缓存流对象
        DataBufferFactory dataBuffer = response.bufferFactory();
        DataBuffer wrap = dataBuffer.wrap(bytes);
        Mono<DataBuffer> monoResult = Mono.fromSupplier(new Supplier<DataBuffer>() {
            @Override
            public DataBuffer get() {
                return wrap;
            }
        });
        return response.writeWith(monoResult);

//        return response.writeWith(Mono.fromSupplier(
//                ()->response.bufferFactory().wrap(result.getBytes(StandardCharsets.UTF_8))
//        ));

    }

    @Override
    public int getOrder() {
        return 200;
    }
}



